package com.zhz.common.feign.config;

import com.zhz.common.feign.FeignClientInitializer;
import com.zhz.common.feign.FeignOptionsUtil;
import com.zhz.common.feign.GlobalFeignFallback;
import feign.Request;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;

/**
 * FeignConfiguration
 * <p>
 * feign 配置类
 *
 * @author zhouhengzhe
 */
@Configuration(proxyBeanMethods = false)
public class FeignConfiguration {


    /**
     * 调整 feign 默认的请求超时时间（方法级别的超时控制见：{@link FeignOptionsUtil}）
     *
     */
    @Bean
    public Request.Options feignRequestOptions(Environment env) {
        int connectTimeout = env.getProperty("ribbon.ConnectTimeout", int.class, 3000);
        int readTimeout = env.getProperty("ribbon.ReadTimeout", int.class, 3000);
        return new Request.Options(connectTimeout, TimeUnit.MILLISECONDS, readTimeout, TimeUnit.MILLISECONDS, true);
    }


    /**
     * 提前加载其他服务
     */
    @Bean
    public FeignClientInitializer feignClientInitializer(SpringClientFactory springClientFactory) {
        return new FeignClientInitializer(springClientFactory);
    }


    /**
     * feign fallback 处理器
     */
    @Bean({"globalFeignFallback", "feignFallbackAspect"})
    public GlobalFeignFallback globalFeignFallback() {
        return new GlobalFeignFallback();
    }

    //配置feign拦截器，解决请求头问题
    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {

            //获取所有浏览器发送的请求属性，请求头赋值到feign
            public void apply(RequestTemplate requestTemplate) {
                //请求属性
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if(attributes != null) {
                    HttpServletRequest request = attributes.getRequest();
                    //获取浏览器发起的请求头
                    Enumeration<String> headerNames = request.getHeaderNames();
                    if (headerNames != null) {
                        while (headerNames.hasMoreElements()) {
                            String name = headerNames.nextElement(); //请求头名称 Authorization
                            String value = request.getHeader(name);//请求头数据 "Bearer b1dbb4cf-7de6-41e5-99e2-0e8b7e8fe6ee"
                            requestTemplate.header(name,value);
                        }
                    }
                }

            }
        };
    }

}
